const formatTime = date => {
    date = new Date(date);
    const year = date.getFullYear()
    const month = date.getMonth() + 1
    const day = date.getDate()
    const hour = date.getHours()
    const minute = date.getMinutes()
    const second = date.getSeconds()
    return [year, month, day].map(formatNumber).join('-') + ' ' + [hour, minute, second].map(formatNumber).join(':')
}
const formatNumber = n => {
    n = n.toString()
    return n[1] ? n : '0' + n
}
/**Y
 * util.format(row.created_at,"YYYY-MM-DD HH:mm:ss")
 * 格式化日期 2018-04-04 11:08
 */
function format(time, fmt) {
    time = time instanceof Date ? time : new Date(time);
    var o = {
        "M+": time.getMonth() + 1, //月份
        "D+": time.getDate(), //日
        "H+": time.getHours(), //小时
        "m+": time.getMinutes(), //分
        "s+": time.getSeconds(), //秒
        "q+": Math.floor((time.getMonth() + 3) / 3), //季度
        S: time.getMilliseconds() //毫秒
    };
    if (/(Y+)/.test(fmt)) {
        fmt = fmt.replace(RegExp.$1, (time.getFullYear() + "").substr(4 - RegExp.$1.length));
    }
    for (var k in o) {
        if (new RegExp("(" + k + ")").test(fmt)) {
            fmt = fmt.replace(RegExp.$1, RegExp.$1.length == 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length));
        }
    }
    return fmt;
}
/**
 * 格式化日期 - （人性化）(附加时间)
 * @param {Number|Date} time
 * @return {string}
 */
function formatSmartTime(time) {
    time = time instanceof Date ? time.getTime() : new Date(time).getTime();
    var diffTime = new Date().getTime() - time;
    //今天凌晨时间戳
    const toDayTime = new Date().setHours(0, 0, 0);
    //昨天凌晨时间戳
    const yesterDayTime = toDayTime - 86400000;
    //明天凌晨时间戳
    const tomorrowTime = toDayTime + 86400000;
    //前天凌晨时间戳
    const beforeYesterdayTime = yesterDayTime - 86400000;
    //后天凌晨时间戳
    const afterTomorrowTime = tomorrowTime + 86400000;
    if (diffTime < 0) {
        diffTime = Math.abs(diffTime);
        //大于一分钟
        if (diffTime < 60000) return "一会儿";
        //大于一分钟小于一小时
        if (diffTime >= 60000 && diffTime < 3600000) return parseInt(diffTime / 60000) + "分钟后";
        //今天
        if (time < tomorrowTime) return "今天" + format(time, "HH:mm");
        //明天
        if (time < afterTomorrowTime) return "明天" + format(time, "HH:mm");
        //后天
        if (time < afterTomorrowTime + 86400000) return "后天" + format(time, "HH:mm");
    } else {
        //小于一分钟
        if (diffTime < 60000) return "刚刚";
        //大于一分钟小于一小时
        if (diffTime >= 60000 && diffTime < 3600000) return parseInt(diffTime / 60000) + "分钟前";
        //今天
        if (time > toDayTime) return "今天" + format(time, "HH:mm");
        //昨天
        if (time > yesterDayTime) return "昨天" + format(time, "HH:mm");
        //前天
        if (time > beforeYesterdayTime) return "前天" + format(time, "HH:mm");
    }
    //月份/日 大于今年开始时间
    const toYearTime = new Date();
    toYearTime.setMonth(0, 0);
    toYearTime.setHours(0, 0, 0, 0);
    const toYearTime2 = new Date(time);
    toYearTime2.setMonth(0, 0);
    toYearTime2.setHours(0, 0, 0, 0);
    if (toYearTime.getTime() == toYearTime2.getTime()) return format(time, "M月D日 HH:mm");
    return format(time, "YYYY年M月D日 HH:mm");
}

function px2rpx(str) {
    return str.replace(/([0-9.]+)px/ig, function(match, x) {
        return (750 * x / 320).toFixed(2) + 'rpx';
    });
}
const rpxToPx = height => {
    var percent = 750 / getSystem().windowWidth; // 当前设备1rpx对应的px值
    return Number(Number(height / percent).toFixed(2));
}
// 获取微信浏览器数据
const getSystem = () => {
    let info = {};
    //判断 基础库版本
    if (!wx.getSystemInfo) {
        wx.showModal({
            title: "提示",
            content: "当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。"
        });
    }
    wx.getSystemInfo({
        success: res => {
            info = res;
        }
    });
    //微信版本信息
    return info;
}

function Rad(d) {
    return d * Math.PI / 180.0; //经纬度转换成三角函数中度分表形式。
}
//计算距离，参数分别为第一点的纬度，经度；第二点的纬度，经度，得到公里
function GetDistance(lat1, lng1, lat2, lng2) {
    var radLat1 = Rad(lat1);
    var radLat2 = Rad(lat2);
    var a = radLat1 - radLat2;
    var b = Rad(lng1) - Rad(lng2);
    var s = 2 * Math.asin(Math.sqrt(Math.pow(Math.sin(a / 2), 2) + Math.cos(radLat1) * Math.cos(radLat2) * Math.pow(Math.sin(b / 2), 2)));
    s = s * 6378.137; // EARTH_RADIUS;
    s = Math.round(s * 10000) / 10000; //输出为公里
    s = s.toFixed(2);
    return s;
}

function array_remove_repeat(a) {
    // 去重
    var r = [];
    for (var i = 0; i < a.length; i++) {
        var flag = true;
        var temp = a[i];
        for (var j = 0; j < r.length; j++) {
            if (temp == r[j]) {
                flag = false;
                break;
            }
        }
        if (flag) {
            r.push(temp);
        }
    }
    return r;
}
//设置主题颜色
function setNavigationBarColor(color) {
    if (color) {
        color = color.toLowerCase(); //变小写
        let frontColor = "#ffffff";
        if (color == "#ffffff") {
            frontColor = "#000000";
        }
        wx.setNavigationBarColor({
            frontColor: frontColor,
            backgroundColor: color,
            animation: {
                duration: 0,
                timingFunc: "linear"
            }
        });
        wx.setStorageSync("color", color);
    } else {
        const color = wx.getStorageSync("color");
        if (color) {
            let frontColor = "#ffffff";
            if (color == "#ffffff") {
                frontColor = "#000000";
            }
            wx.setNavigationBarColor({
                frontColor: frontColor,
                backgroundColor: color,
                animation: {
                    duration: 0,
                    timingFunc: "linear"
                }
            });
        }
    }
}
//生成从minNum到maxNum的随机数
function randomNum(minNum, maxNum) {
    switch (arguments.length) {
        case 1:
            return parseInt(Math.random() * minNum + 1, 10);
            break;
        case 2:
            return parseInt(Math.random() * (maxNum - minNum + 1) + minNum, 10);
            break;
        default:
            return 0;
            break;
    }
}
//跳转
function navigateTo(targetType, targetUrl, targetImg) {
    //跳转页面
    if (targetType == "page") {
        let url = "";
        try {
            const target_page = wx.getStorageSync("target_page");
            if (target_page) {
                if (target_page == "index") {
                    wx.setStorageSync("target_page", "index2");
                    if (targetUrl.indexOf("?")>=0) {
                        url = targetUrl;
                    }else{
                        url = `/pages/index2/index?id=${targetUrl}`;
                    }
                } else {
                    wx.setStorageSync("target_page", "index");
                    if (targetUrl.indexOf("?")>=0) {
                        url = targetUrl;
                    }else{
                        url = `/pages/index/index?id=${targetUrl}`;
                    }
                }
            } else {
                wx.setStorageSync("target_page", "index2");
                if (targetUrl.indexOf("?")>=0) {
                        url = targetUrl;
                }else{
                    url = `/pages/index2/index?id=${targetUrl}`;
                }
            }
        } catch (e) {
            // Do something when catch error
        }
        // console.log('url',url);
        wx.reLaunch({
            url: url
        });
        return;
    }
    //自定义页面
    if (targetType == 'diypage') {
        wx.navigateTo({
            url: target_url
        });
        return;
    }
    //跳转小程序
    if (targetType == 'wxa') {
        wx.navigateToMiniProgram({
            appId: targetUrl,
            envVersion: 'release',
            success(res) {
                // 打开成功
            },
            fail(err) {
                console.log(err);
                if (targetImg) {
                    wx.previewImage({
                        current: targetImg, // 当前显示图片的http链接
                        urls: [targetImg] // 需要预览的图片http链接列表
                    })
                }
            }
        })
        // return;
    }
    //拨号
    if (targetType == 'tel') {
        wx.makePhoneCall({
            phoneNumber: targetUrl.toString() //仅为示例，并非真实的电话号码
        })
        return;
    }
    //图片
    if (targetImg) {
        wx.previewImage({
            current: targetImg, // 当前显示图片的http链接
            urls: [targetImg] // 需要预览的图片http链接列表
        })
    }
}
// 16进制颜色值转换为rgb
function colorRgb(sColor) {
    var reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    if (sColor && reg.test(sColor)) {
        sColor = sColor.toLowerCase();
        if (sColor.length === 4) {
            var sColorNew = "#";
            for (var i = 1; i < 4; i += 1) {
                sColorNew += sColor
                    .slice(i, i + 1)
                    .concat(sColor.slice(i, i + 1));
            }
            sColor = sColorNew;
        }
        //处理六位的颜色值
        var sColorChange = [];
        for (var i = 1; i < 7; i += 2) {
            sColorChange.push(parseInt("0x" + sColor.slice(i, i + 2)));
        }
        return sColorChange.join(",");
        // return "rgb(" + sColorChange.join(",") + ")";
    } else {
        return sColor;
    }
}
module.exports = {
    formatTime,
    formatSmartTime,
    getSystem,
    px2rpx,
    rpxToPx,
    navigateTo,
    array_remove_repeat,
    setNavigationBarColor,
    randomNum,
    GetDistance,
    colorRgb
}